import { ReactSortable } from 'react-sortablejs'
import { nanoid } from 'nanoid'
import Layout from './layout'

import './index.less'

export default ({
  fieldList = [],
  currentField = [],
  onFieldChange = () => {},
  handleChooseField = () => {},
}) => {
  const handleDelete = (e, id) => {
    e.stopPropagation()
    const newFieldList = [...fieldList]
    const curIndex = newFieldList.findIndex((item) => item.id === id)
    if (curIndex !== -1) {
      const deleteItem = newFieldList.splice(curIndex, 1)
      if (deleteItem?.[0]?.id === currentField?.id) {
        handleChooseField({})
      }
      onFieldChange(newFieldList)
    }
  }
  return (
    <ReactSortable
      list={fieldList || []}
      animation={200}
      group={{
        name: 'sort-field',
      }}
      setList={(list) =>
        onFieldChange(
          list.map((item) => ({
            ...item,
            id: item?.id ? item?.id : nanoid(),
          }))
        )
      }
      sort={true}
      forceFallback={true}
      className="field-center"
    >
      {fieldList?.length === 0 ? (
        <div className="main-tooltip">请选择左侧的组件</div>
      ) : (
        fieldList.map((item, index) => (
          <div
            className="main-field"
            style={{
              border: currentField?.id === item.id ? '1px solid #1890ff' : '',
              background: currentField?.id === item.id ? '#F9FBFF' : '',
            }}
            key={index}
            onClick={() => handleChooseField}
          >
            <Layout field={item} />
          </div>
        ))
      )}
    </ReactSortable>
  )
}
